package com.cn.jx.manager.controller;

import java.text.MessageFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.jx.base.SessionUser;
import com.jx.jpaQuery.ConvertCondition;
import com.jx.jpaQuery.PageCondition;
import com.jx.jpaQuery.QueryCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cn.jx.common.controller.BaseController;

import com.cn.jx.common.util.page.PageObj;

import com.cn.jx.manager.form.UserForm;
import com.cn.jx.manager.form.UserOrgJobForm;
import com.cn.jx.manager.po.Contact;
import com.cn.jx.manager.po.User;
import com.cn.jx.manager.service.mtn.IOrgServiceMtn;
import com.cn.jx.manager.service.mtn.IUserServiceMtn;
import com.cn.jx.manager.service.query.IRoleServiceQry;
import com.cn.jx.manager.service.query.IUserServiceQry;
import com.jx.enumType.DataGrideTypeEnum;
import com.jx.enumType.ResourceEnum;
import com.jx.model.MenuEntry;
import com.jx.util.Constant;
import com.jx.util.FormValidat;
import com.jx.util.MapObject;
import com.jx.util.Response;
import com.jx.util.Utility;

/**
 * 
 * @author 姜旭
 * @version v1.11.20.2019
 * @since
 *        <p> 创建时间：2019年12月1日
 *        <p> 功能描述：
 *        <p> 官方网站：management/admin/index
 *        <p> 邮箱地址：524577360@qq.com
 */
@Controller
@RequestMapping("/admin/uoj/user/")
public class UserController extends BaseController {

	private static final String _PAGE_PATH = "userorgjob/";

	/** 定义{@link IUserService userService <tt>用户接口</tt>} */
	@Autowired
	private IUserServiceQry userServiceQry;
	
	/** 定义{@link IUserService userService <tt>用户接口</tt>} */
	@Autowired
	private IUserServiceMtn userServiceMtn;
	@Autowired
	protected IRoleServiceQry roleServiceQry;
	
	@Autowired
	private IOrgServiceMtn orgServiceMtn;

	/**
	 * @Title:userList 
	 * @Description:TODO(跳转到页面) 
	 * <p>邮箱地址: 524577360@qq.com @throws
	 */
	@RequestMapping("list/{path}")
	public String userList(Model model, HttpServletRequest request,@PathVariable(value = "path") String path) {
		SessionUser sessUser = getSessionUser(request);
		setModelColumns(model, DataGrideTypeEnum.USER_MGR);
		if(!"recycle".equals(path)) {
			setModelColumns(model, DataGrideTypeEnum.USER_ORG_JOB);
		}
		setModelPermit(model,ResourceEnum.USER_MGR,sessUser.getResourceCodeList());
		return MessageFormat.format("{0}{1}", _PAGE_PATH,"recycle".equals(path)?"user/userrecycle":"userlist");
	}

	/**
	 * 
	 * @Title:editWindow
	 * @Description:TODO(跳转都编辑)
	 * <p>邮箱地址: 524577360@qq.com
	 */
	@RequestMapping("edit")
	public String editWindow(Model model, String id, String orgId, String orgName) {
		// id存在 则为修改编辑
		User user = null;
		if (Utility.isNotBlank(id)) {
			user = userServiceQry.getUserById(id);
		}
		model.addAttribute("orgId", orgId);
		model.addAttribute("orgName", orgName);
		model.addAttribute("res", user);
		return _PAGE_PATH + "user/useredit";
	}

	
	/**
	 * 
	* @Title: allotJobWindow
	* @Description: TODO(跳转到分派岗位组织)
	* <p>邮箱地址：524577360@qq.com
	* @param model
	* @throws
	 */
	@RequestMapping("allotJob")
	public String allotJobWindow(Model model,String orgId,String userId) {
		model.addAttribute("userId", userId);
		return _PAGE_PATH + "user/userallotjob";
	}
	
	/**
	 * 
	* @Title: allotRoleWindow
	* @Description: TODO(跳转到分派角色)
	* <p>邮箱地址：524577360@qq.com
	* @throws
	 */
	@RequestMapping("allotRole")
	public String allotRoleWindow(Model model,String id) {
		model.addAttribute("userId", id);
		return _PAGE_PATH + "user/userallotrole";
	}
	
	/**
	 * 
	* @Title:contactWindow
	* @Description:TODO(基本信息)
	* <p>邮箱地址: 524577360@qq.com
	 */
	@RequestMapping("contact")
	public String contactWindow(Model model,String id) {
		model.addAttribute("userId", id);
		return _PAGE_PATH + "user/userbaseinfo";
	}
	
	/**
	 * 
	* @Title:personInfo
	* @Description:TODO(跳转到个人信息修改)
	* <p>邮箱地址: 524577360@qq.com
	* @throws
	 */
	@RequestMapping("person/infor")
	public String personInfo(Model model,HttpServletRequest request) {
		SessionUser sessUser = getSessionUser(request);
		String uid=sessUser.getUserId();
		if(Constant._SUPER.equals(uid)){
			model.addAttribute("msg","当前为超级管理员，不能修改登录人信息！！");
		}else{
			User user=userServiceQry.getUserById(uid);
			model.addAttribute("user",user);
			
			Contact ct=sessUser.getContact();
			if(Utility.isNotBlank(ct.getId())){
				model.addAttribute("contact",ct);
			}
			model.addAttribute("msg","");
		}
		return _PAGE_PATH + "user/userInfoPerfect";
	}

	/**
	 * 
	* @Title:personPwd
	* @Description:TODO(修改密码)
	* <p>邮箱地址: 524577360@qq.com
	 */
	@RequestMapping("person/pwd")
	public String personPwd(Model model) {
		return _PAGE_PATH + "user/userPwd";
	}
	/**
	 * 
	 * @Title:userList 
	 * @Description:TODO(用户分页列表) 
	 * <p>邮箱地址: 524577360@qq.com 
	 */
	@RequestMapping("listData/{path}")
	@ResponseBody
	public PageObj<MapObject> userList(Model model,@PathVariable(value = "path") String path, PageCondition page) {
		QueryCondition cond = ConvertCondition.initCondition(page, path);
		try {
			PageObj<MapObject> pageuser = userServiceQry.findUserByPageAndParams(cond);
			return pageuser;
		} catch (Exception e) {
			log.debug(e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	* @Title:userOrgJobList
	* @Description:TODO(关系表)
	* <p>邮箱地址: 524577360@qq.com
	* PageObj<Map<String,Object>>
	* @throws
	 */
	@RequestMapping("listData/user/org/job")
	@ResponseBody
	public List<MapObject> userOrgJobList(Model model, String id) {
		try {
			List<MapObject> pageuser = userServiceQry.findUserOrgJobByPageAndParams(id);
			return pageuser;
		} catch (Exception e) {
			log.debug(e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @Title:addUser 
	 * @Description:TODO(添加用户) 
	 * <p>邮箱地址: 524577360@qq.com 
	 * @throws
	 */
	@RequestMapping("addOrUpdate")
	@ResponseBody
	public Response addUser(Model model, HttpServletRequest request, UserForm userForm) {
		SessionUser sessUser = getSessionUser(request);
		// 表单验证
		try {
			FormValidat.exec(userForm);
			userForm.setOperatUser(sessUser.getUserId());
			userServiceMtn.saveOrUpdateUser(userForm);
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}

	/**
	 * 
	 * @Title:delUser 
	 * @Description:TODO(删除用户) 
	 * <p>邮箱地址: 524577360@qq.com 
	 * @throws
	 */
	@RequestMapping("delete")
	@ResponseBody
	public Response delUser(Model model, HttpServletRequest request, String ids) {
		SessionUser sessUser = getSessionUser(request);
		try {
			FormValidat.validId(ids);
			List<String> list = JSON.parseArray(ids, String.class);
			userServiceMtn.delUser(list, sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}

	/**
	 * 
	 * @Title:removeUser 
	 * @Description:TODO(彻底移除) 
	 * <p>邮箱地址: 524577360@qq.com 
	 * @throws
	 */
	@RequestMapping("remove")
	@ResponseBody
	public Response removeUser(Model model, HttpServletRequest request, String ids) {
		SessionUser sessUser = getSessionUser(request);
		try {
			FormValidat.validId(ids);
			List<String> list = JSON.parseArray(ids, String.class);
			userServiceMtn.removeUser(list, sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}

	/**
	 * 
	 * @Title:recoverUser 
	 * @Description:TODO(回收站找回) 
	 * <p>邮箱地址: 524577360@qq.com 
	 * @throws
	 */
	@RequestMapping("recover")
	@ResponseBody
	public Response recoverUser(Model model, HttpServletRequest request, String ids) {
		SessionUser sessUser = getSessionUser(request);
		try {
			FormValidat.validId(ids);
			List<String> list = JSON.parseArray(ids, String.class);
			userServiceMtn.recoverUser(list, sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}

	/**
	 * 
	 * @Title:getUserById 
	 * @Description:TODO(获取用户根据id) 
	 * <p>邮箱地址: 524577360@qq.com 
	 * @throws
	 */
	@RequestMapping("get")
	@ResponseBody
	public Response getUserById(Model model, HttpServletRequest request, String id) {
		User uf = userServiceQry.getUserById(id);
		return Response.Success(uf);
	}

	/**
	 * @Title:removeRole
	 * @Description:TODO(移除角色 清空回收站)
	 * <p>  邮箱地址: 524577360@qq.com 
	 *  @throws
	 */
	@RequestMapping("removeAll")
	@ResponseBody
	public Response removeAllUser(Model model, HttpServletRequest request) {
		SessionUser sessUser = getSessionUser(request);
		try {
			userServiceMtn.removeUserAll(sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
	
	/**
	 * 
	* @Title:allotJob
	* @Description:TODO(分配)
	* <p>邮箱地址: 524577360@qq.com
	* Response
	* @throws
	 */
	@RequestMapping("org/job/relation")
	@ResponseBody
	public Response allotJob(Model model, HttpServletRequest request,UserOrgJobForm uoj) {
		SessionUser sessUser = getSessionUser(request);
		try {
			FormValidat.exec(uoj);
			uoj.setOperatUser(sessUser.getUserId());
			userServiceMtn.allotOrgJobByUser(uoj);
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
	
	/**
	 * 
	* @Title:allotJobDel
	* @Description:TODO(删除关系)
	* <p>邮箱地址: 524577360@qq.com
	* @param model
	* @param request
	* @param uoj
	* @return
	* Response
	* @throws
	 */
	@RequestMapping("org/job/relation/delete")
	@ResponseBody
	public Response allotJobDel(Model model, HttpServletRequest request, String ids) {
		SessionUser sessUser = getSessionUser(request);
		try {
			FormValidat.validId(ids);
			List<String> list = JSON.parseArray(ids, String.class);
			userServiceMtn.delUOJbyids(list,sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
	
	/**
	 * 
	* @Title: getAllRole
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* <p>邮箱地址：524577360@qq.com
	* @throws
	 */
	 @RequestMapping("getAllRoleByUser")
	 @ResponseBody
	 public List<MenuEntry> getAllRole(Model model,String userId) {
		 List<MenuEntry> res= roleServiceQry.findAllRole(userId);
	     return res;
	 }
	
	/**
	 * 
	* @Title: allotRole
	* @Description: TODO(角色关系)
	* <p>邮箱地址：524577360@qq.com
	* @throws
	 */
	@RequestMapping("role/relation")
	@ResponseBody
	public Response allotRole(Model model, HttpServletRequest request, String userId) {
		SessionUser sessUser = getSessionUser(request);
		try {
			String[] roleId = request.getParameterValues("roleId[]");
			userServiceMtn.addUserRole(userId,roleId,sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
	
	@RequestMapping("set/uoj/major")
	@ResponseBody
	public Response setMajor(Model model, HttpServletRequest request, String userId,String orgId,String jobId) {
		SessionUser sessUser = getSessionUser(request);
		try {
			userServiceMtn.setMajorByuoj(userId,orgId,jobId,sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
	
	/**
	 * 
	* @Title: allotLeader
	* @Description: TODO(设置领导
	* <p>邮箱地址：524577360@qq.com
	* @return Response 返回类型
	* @throws
	 */
	@RequestMapping("allotLeader")
	@ResponseBody
	public Response allotLeader(Model model, HttpServletRequest request, String id,String orgId) {
		SessionUser sessUser = getSessionUser(request);
		try {
			orgServiceMtn.updateOrgLeader(orgId, id,sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
}
